package com.zhiliao.component.beetl.fun;

import org.beetl.core.Context;
import org.beetl.core.Function;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description:
 *
 * @author qirong
 * @date 2018-10-26
 */
public class PrintTimeFunction implements Function {

    private final static SimpleDateFormat TIME_STAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat MY_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日");

    @Override
    public String call(Object[] params, Context context) {
        if (params.length != 1){
            throw new RuntimeException("length of params must be 1 !");
        }
        if (params[0].toString().length()==0){
            return null;
        }
    
        return getNiceDate((Date)params[0]);
    }

    public static String getNiceDate( Date date) {
        if (null == date) {
            return "";
        }
        String result = null;
        long currentTime = System.currentTimeMillis() - date.getTime();
        int time = (int)(currentTime / 1000);
        int min = 60;
        int hour = 3600;
        int day = 86400;
        int ten = 864000;
        if(time < min) {
            result = "刚刚";
        } else if(time >= min && time < hour) {
            result = time/min + "分钟前";
        } else if(time >= hour && time < day) {
            result = time/hour + "小时前";
        } else if(time >= day && time < ten) {
            result = time/day + "天前";
        } else{
            result = MY_DATE_FORMAT.format(date);
        }
        return result;
    }
}
